package cn.stylefeng.guns.modular.api;

import cn.stylefeng.guns.alipay.AliPayApi;
import cn.stylefeng.guns.config.redis.redis.util.Redishandler0;
import cn.stylefeng.guns.core.PayModeType;
import cn.stylefeng.guns.core.RecoverConst;
import cn.stylefeng.guns.modular.business.model.dto.TransactionLogDTO;
import cn.stylefeng.guns.modular.business.service.UserTransactionLogService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * @Author pzp .
 * @Date 2019/8/312:51
 */

@RestController
@RequestMapping("/gunsApi/transactionLog")
public class TransactionLogApi extends BaseController {

    @Autowired
    private UserTransactionLogService userTransactionLogService;


    @Autowired
    private Redishandler0 redishandler0;

    @ApiOperation("提现记录")
    @PostMapping("/record")
    public ResponseData record(@RequestBody TransactionLogDTO transactionLogDTO) {
        if (null == transactionLogDTO.getUserId()) {
            return ResponseData.error("请输入用户id");
        }
        if (null == transactionLogDTO.getCurrent() || null == transactionLogDTO.getSize()) {
            return ResponseData.error("请输入分页参数");
        }
        return ResponseData.success(userTransactionLogService.record(transactionLogDTO));
    }

    @ApiOperation("提现")
    @GetMapping("/cashOut")
    public ResponseData cashOut(@RequestParam Long userId) {
        return ResponseData.success(userTransactionLogService.cashOut(userId));
    }

    @ApiOperation("确认提现")
    @PostMapping("/confirmCashOut")
    public ResponseData confirmCashOut(@RequestParam Long userId, @RequestParam String orderNo, @RequestParam BigDecimal money, @RequestParam Integer payMode, @RequestParam String account) {
        if (payMode == null) {
            return ResponseData.error("请选择支付方式");
        }
        if (StringUtils.isBlank(account)) {
            return ResponseData.error("请输入账户");
        }
        if (new BigDecimal(0).compareTo(money) >= 0) {
            return ResponseData.error("金额必须大于0");
        }
        if (StringUtils.isBlank(orderNo)) {
            return ResponseData.error("请输入订单号");
        }

        try {
            userTransactionLogService.confirmCashOut(userId, orderNo, money, payMode, account);
        } catch (Exception e) {
            if (redishandler0.hasKey(RecoverConst.USER_ORDER_REDIS_KEY + orderNo)) {
                redishandler0.incr(RecoverConst.USER_ORDER_REDIS_KEY, orderNo, -1);
            }
            return ResponseData.error(e.getMessage());

        }
        return ResponseData.success();
    }

}
